using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public enum MissionEventType
{
	None,
	Planet,
}

public class EventManager : MonoBehaviour {
	
	MissionEvent[] EventList;
	SortedList<int,MissionEvent> EventDictionary;
	Queue<MissionEvent> RuningQueue;
	MissionEvent DoingEvent;
	int EventNum;
	public Transform AVGPrefabs;
	public MissionEventType eventType;
	public GameObject CallBack;
	
	// Use this for initialization
	void Start () {
		RuningQueue = new Queue<MissionEvent>();
		EventList = this.GetComponents<MissionEvent>();
	}
	
	/// <summary>
	/// 开始任务.
	/// </summary>
	public void StartEvent(){
		if(EventList == null)
			Start ();
		
		foreach(MissionEvent m in EventList)
		{
			foreach(AcceptMissionData a in GameData.mainData.Mission)
			{
				if(m.MissionID == a.ID && m.MissionSetp == a.Setp)
				{
					RuningQueue.Enqueue(m);
					Debug.Log("Start the Event: " + m.AddID);
					break;
				}
			}
		}
		
		if(RuningQueue.Count > 0)
			RuningEvent();
		else
			CallBack.SendMessage("OnEventFinish",eventType);
	}
	
	void RuningEvent(){
		EventNum ++;
		if(RuningQueue.Count == 0)
		{
			EventNum = 0;
			CallBack.SendMessage("OnEventFinish",eventType);
		}
		else
		{
			//提取队列.
			DoingEvent = RuningQueue.Dequeue();
			DoingEvent.OnEventStart();
			if(DoingEvent.RunAVGScript != null)
			{
				if(EventNum == 1)
					CallBack.SendMessage("OnEvnetStart",eventType,SendMessageOptions.DontRequireReceiver);
				Instantiate(AVGPrefabs);
				var obj = GameObject.FindGameObjectWithTag("AVGSystem");
				obj.GetComponent<AVGManager>().RunScript(this,DoingEvent.RunAVGScript);
			}
			else
				RuningNextEvent();
		}
	}
	
	public void RuningNextEvent(){
		GameObject.Destroy(GameObject.FindGameObjectWithTag("AVGSystem"));
		DoingEvent.OnEventEnd();
		DoingEvent = null;
		RuningEvent();
	}
}
